package cn.nawang.ebeim.api.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.nawang.ebeim.api.bean.CustomerBean;
import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.domain.Ca;
import cn.nawang.ebeim.api.domain.CaCustomer;
import cn.nawang.ebeim.api.domain.Customer;
import cn.nawang.ebeim.api.domain.CustomerEncryption;
import cn.nawang.ebeim.api.domain.Department;
import cn.nawang.ebeim.api.domain.SalesPackage;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.repository.CaCustomerRepository;
import cn.nawang.ebeim.api.repository.CaRepository;
import cn.nawang.ebeim.api.repository.CustomerEncryptionRepository;
import cn.nawang.ebeim.api.repository.CustomerRepository;
import cn.nawang.ebeim.api.repository.DepartmentRepository;
import cn.nawang.ebeim.api.repository.SalesPackageRepository;
import cn.nawang.ebeim.api.repository.UserRepository;
import cn.nawang.ebeim.api.repository.impl.CaQueryRepositoryImpl;
import cn.nawang.ebeim.api.repository.impl.CustomerQueryImpl;
import cn.nawang.ebeim.api.repository.impl.UserQueryImpl;
import cn.nawang.ebeim.api.service.CustomerService;
import cn.nawang.ebeim.api.utils.AesPassword;
import cn.nawang.ebeim.api.utils.Constant;
import cn.nawang.ebeim.api.utils.DateOperate;
import cn.nawang.ebeim.api.utils.DateUtils;
import cn.nawang.ebeim.api.utils.Util;
import cn.nawang.ebeim.key.NaWangKey;
import cn.nawang.ebeim.key.RandomKeyGenerator;

@Service("customerService")
public class CustomerServiceImpl implements CustomerService {

  @Autowired
  private CustomerQueryImpl customerQueryImpl;
  @Autowired
  private CustomerRepository customerRepository;
  @Autowired
  private CaRepository caRepository;
  @Autowired
  private CaCustomerRepository caCustomerRepository;
  @Autowired
  private DepartmentRepository departmentRepository;
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private UserQueryImpl userQueryImpl;
  @Autowired
  private SalesPackageRepository salesPackageRepository;
  
  @Autowired
  private CustomerEncryptionRepository customerEncryptionRepository;
  
  @Autowired
  private CaQueryRepositoryImpl caQueryRepositoryImpl;
  
  public PageList getCustomers(Pages page) {
    return customerQueryImpl.findUserList(page);
  }

  @Override
  public boolean saveAdminInfo(User user,String companyName,String useType,
                               String CaIdJoinLabId,String createUserId,int maxCopys,
                               String salesPacakgeId,int authTime) {
    try{     
      Date d = new Date();
      SalesPackage salesPackage=salesPackageRepository.findOne(salesPacakgeId);
      //新增客户
      String customerKey=RandomKeyGenerator.generate();
      Customer customer = new Customer();
      customer.setId(UUID.randomUUID().toString());
      customer.setName(companyName);
      customer.setSpace(Integer.valueOf(salesPackage.getSpaceSize()).toString());
      customer.setSpaceCapacity("0");
      customer.setMaxCopys(maxCopys);;
      customer.setCreateTime(new Date().getTime());
      customer.setCustomerKey(customerKey);
      customer.setSalesPacakgeId(salesPacakgeId);
      
      //  新增客户加密方式
      //  给客户秘钥加密
      String encCustomerKey=NaWangKey.encryptKey(customerKey);
      String password=AesPassword.getAesPassword();
      String encryptionKey=NaWangKey.encryptKey2(encCustomerKey, password);
      CustomerEncryption customerEncryption=new CustomerEncryption();
      customerEncryption.setCustomerId(customer.getId());
      customerEncryption.setEncryptionType(Constant.ENCRYPTION_TYPE_ZERO);
      customerEncryption.setEncryptionKey(encryptionKey);
      customerEncryptionRepository.save(customerEncryption);
      
      String[] CaIds=CaIdJoinLabId.split("\r\n");
      for(String CaId:CaIds){
        Ca ca = new Ca();
        ca.setCaType("00");
        ca.setCreateTime(d.getTime());
        ca.setCreateUserId(createUserId);
        ca.setCaId(CaId.split(",")[1]);
        ca.setLabId(CaId.split(",")[0]);
        ca.setLabType(CaId.split(",")[2]);
        ca.setIsBind(Constant.IS_BIND_ZERO);
        ca.setAuthTime(authTime);
        // 设置授权生效时间
        ca.setAuthStartTime(new Date().getTime());
        // 设置授权过期时间
        ca.setAuthEndTime(DateUtils.getYearAfterLong(authTime));
        caRepository.save(ca);
        
        CaCustomer cc = new CaCustomer();
        cc.setId(UUID.randomUUID().toString());
        cc.setCreateTime(d.getTime());
        cc.setCreateUserId(createUserId);
        cc.setCustomerId(customer.getId());
        cc.setLabId(ca.getLabId());
        cc.setUseType("0");
        caCustomerRepository.save(cc);
      }
      //创建基础数据      
      
      Department dept = new Department();
      dept.setCreateTime(d.getTime());
      dept.setCreateUserId(createUserId);
      dept.setCustomerId(customer.getId());
      dept.setHasChildren((short)0);
      dept.setIOrder(0);
      dept.setLevel(0);
      dept.setParentId(0);
      dept.setName(companyName);//将公司名称默认为部门名称
      dept = departmentRepository.save(dept);
      
      //新增用戶管理員
      user.setCreateTime(DateOperate.formatDateToString(d, DateOperate.DATE_TIME_STYLE_All));
      user.setCreateUserId(createUserId);
      user.setCustomerId(customer.getId());
      user.setDepartmentId(dept.getId());
      user.setIsUpdateDefaultPwd(Constant.NO);
      user.setStatus(Constant.USER_STATUS_TYPE_ZERO);
      user.setId(String.valueOf(userQueryImpl.findMaxRecordId()));
      user.setPassword(Util.hash(user.getPassword()));
      user.setRole(Constant.ROLE_ADMIN);
      
      user.setLabId(CaIds[0].split(",")[0]);
      user.setLabType(CaIds[0].split(",")[2]);
      
      user.setIsFirstLogin(Constant.USER_IS_FIRST_LOGIN_YES);
      user.setSpaceSize(customer.getSpace());
      user.setSafeLevel(Constant.USER_SAFE_LEVEL_ZERO);
      user.setSpaceCapacity(Constant.USER_SAFE_LEVEL_ZERO);
      userRepository.save(user);
      
      Ca ca=caRepository.findOne(CaIds[0].split(",")[1]);
      ca.setIsBind(Constant.IS_BIND_ONE);
      caRepository.save(ca);
      customer = customerRepository.save(customer);
      return true;
    }catch(Exception ex){
      ex.printStackTrace();
    }
    return false;
  }

  @Override
  public Customer findCustomerByName(String companyName) {
    return customerQueryImpl.findCustomerByName(companyName);
  }

  @Override
  public PageList findCustomerList(Pages page) {
    return customerQueryImpl.findCustomerList(page);
  }

  @Override
  public boolean batchTransferUser(int departId, String userIdStr) {
    return userQueryImpl.updateUserDept(departId, userIdStr);
  }

  @Override
  public Customer findCustomerByTerminalId(String terminalId) {    
    return customerQueryImpl.findCustomerByTerminalId(terminalId);
  }

  @Override
  public Customer findOne(String id) {
    return customerRepository.findOne(id);
  }

  @Override
  public void updata(Customer customer) {   
    customerRepository.save(customer);
  }

  @Override
  public CustomerBean findCustomerBean(String id) {
    CustomerBean customerBean=customerQueryImpl.getCustomerBean(id);
    List<Ca> list = caQueryRepositoryImpl.findByCustomerIdAll(id);
    customerBean.setList(list);
    return customerBean;
  }

}
